package com.example.mybatisplus.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.example.mybatisplus.common.JsonResponse;
import com.example.mybatisplus.service.AnimeVedioService;
import com.example.mybatisplus.model.domain.AnimeVedio;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.HashMap;
import java.util.Map;


/**
 *
 *  前端控制器
 *
 *
 * @author lxp
 * @since 2022-02-28
 * @version v1.0
 */
@Controller
@RequestMapping("/animeVedio")
public class AnimeVedioController {

    private final Logger logger = LoggerFactory.getLogger( AnimeVedioController.class );

    @Autowired
    private AnimeVedioService animeVedioService;

    /**
    * 描述：根据Id 查询
    *
    */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getById(@PathVariable("id") Long id)throws Exception {
        AnimeVedio  animeVedio =  animeVedioService.getById(id);
        return JsonResponse.success(animeVedio);
    }

    /**
    * 描述：根据Id删除
    *
    */
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    @ResponseBody
    public JsonResponse deleteById(@PathVariable("id") Long id) throws Exception {
        animeVedioService.removeById(id);
        return JsonResponse.success(null);
    }


    /**
    * 描述：根据Id 更新
    *
    */
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    @ResponseBody
    public JsonResponse updateAnimeVedio(@PathVariable("id") Long  id,@RequestBody AnimeVedio  animeVedio) throws Exception {
        animeVedio.setId(id);
        animeVedioService.updateById(animeVedio);
        return JsonResponse.success(null);
    }


    /**
    * 描述:创建AnimeVedio
    *
    */
    @RequestMapping(value = "", method = RequestMethod.POST)
    @ResponseBody
    public JsonResponse create(@RequestBody AnimeVedio  animeVedio) throws Exception {
        animeVedioService.save(animeVedio);
        return JsonResponse.success(null);
    }



    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        Assert.notNull(file, "上传文件不能为空");
        String filepath = System.getProperty("user.dir")+"/src/main/resources/static/uploadFile/";//上传到这个文件夹
        //System.out.println("保存路径:"+ filepath);
        String filename = System.currentTimeMillis()+file.getOriginalFilename();
        //System.out.println("文件名:"+ filename);

        //确保路径存在
        File file2 = new File(filepath);
        //System.out.println("文件路徑測試："+file2.getPath());
        if (!file2.exists()) {
            file2.mkdirs();
        }
        String savepath = filepath+"\\"+filename;

        savepath = savepath.substring(savepath.lastIndexOf("/")+1);
        //System.out.println("保存路径測試:"+savepath);
        savepath = savepath.replace("\\", "/");
        //System.out.println("保存路径:"+savepath);
        Map map = new HashMap<String,Object>();
        // String formerId = request.getParameter("formerId");
        long Fid = 15;
        // long Fid = Long.parseLong(formerId);
        try {
            //保存文件到服务器
            System.out.println("測試1"+savepath);
            String realpath = file2.getPath() + "\\" +filename;
            System.out.println("測試2"+realpath);
            file.transferTo(new File(realpath));
            //保存到数据库
            System.out.println("測試3"+savepath);
            AnimeVedio animeVedio=new AnimeVedio();
            animeVedio.setWork(savepath);
            animeVedio.setId(Fid);
            QueryWrapper<AnimeVedio> wrapper = new QueryWrapper<>();
            wrapper.eq("id",Fid);
            AnimeVedio list1= animeVedioService.getOne(wrapper);
            if (list1==null){
                animeVedioService.saveOrUpdate(animeVedio);
            }else{
                animeVedio.setId(list1.getId());
                animeVedioService.updateById(animeVedio);
            }

            //返回json
            map.put("msg","ok");
            map.put("code",200);
            //   加不加这个都行
//            map.put("data",new HashMap<String,Object>(){
//                {
//                    put("src",savepath);
//                }
//            });

        } catch (Exception e) {
            map.put("msg","error");
            map.put("code",0);
            e.printStackTrace();
        }

        return map;
    }
}

